//
//  CLNumberButton.m
//  CLPPbutton
//
//  Created by 小草毋正 on 2018/3/16.
//  Copyright © 2018年 zwc. All rights reserved.
//

#import "CLNumberButton.h"


@interface CLNumberButton ()<UITextFieldDelegate> {
    CGFloat _width;
    CGFloat _height;
}

@property (nonatomic, strong) NSTimer *timer;

/** 加按钮 */
@property (nonatomic, strong) UIButton *increaseButton;

/** 减按钮 */
@property (nonatomic, strong) UIButton *decreaseButton;

/** 数字显示框 */
@property (nonatomic, strong) UITextField *textField;


@end



@implementation CLNumberButton


#pragma mark- ==== Init ====

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self setupUI];
    }
    return self;
}

+ (instancetype)numberButtonWithFrame:(CGRect)frame {
    return [[self alloc] initWithFrame:frame];
}


- (void)setupUI {
    
    _minValue = 1;
    _maxValue = 10;
    _buttonTitleFont = 17;
    _inputFieldFont = 15;
    _longPressSpaceTime = 0.1f;
    
    // 创建按钮
    _increaseButton = [self creatButton];
    _decreaseButton = [self creatButton];
    
    // 输入框
    _textField = [[UITextField alloc] init];
    _textField.delegate = self;
    _textField.textAlignment = NSTextAlignmentCenter;
    _textField.keyboardType = UIKeyboardTypeNumberPad;
    _textField.font = [UIFont systemFontOfSize:_inputFieldFont];
    _textField.text = [NSString stringWithFormat:@"%ld", _minValue];
    
    [self addSubview:_increaseButton];
    [self addSubview:_decreaseButton];
    [self addSubview:_textField];
    
    self.clipsToBounds = YES;
    self.layer.cornerRadius = 3.f; 
}



- (UIButton *)creatButton {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.titleLabel.font = [UIFont systemFontOfSize:_buttonTitleFont];
    [button addTarget:self action:@selector(touchDown:) forControlEvents:UIControlEventTouchDown];
    [button addTarget:self action:@selector(touchUp:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside|UIControlEventTouchCancel];
    return button;
}


#pragma mark- ==== Set Get ====

- (void)setIncreaseTitle:(NSString *)increaseTitle {
    _increaseTitle = increaseTitle;
    [self.increaseButton setTitle:increaseTitle forState:UIControlStateNormal];
}

- (void)setDecreaseTitle:(NSString *)decreaseTitle {
    _decreaseTitle = decreaseTitle;
    [self.decreaseButton setTitle:decreaseTitle forState:UIControlStateNormal];
}

- (void)setIncreaseImage:(UIImage *)increaseImage {
    _increaseImage = increaseImage;
    [self.increaseButton setBackgroundImage:increaseImage forState:UIControlStateNormal];
}

- (void)setDecreaseImage:(UIImage *)decreaseImage {
    _decreaseImage = decreaseImage;
    [self.decreaseButton setBackgroundImage:decreaseImage forState:UIControlStateNormal];
}

- (void)setBorderColor:(UIColor *)borderColor {
    _borderColor = borderColor;
    
    self.layer.borderWidth = .5f;
    self.layer.borderColor = borderColor.CGColor;
    
    _increaseButton.layer.borderWidth = .5f;
    _increaseButton.layer.borderColor = borderColor.CGColor;
    
    _decreaseButton.layer.borderWidth = .5f;
    _decreaseButton.layer.borderColor = borderColor.CGColor;
}

- (void)setEditing:(BOOL)editing {
    _editing = editing;
    self.textField.enabled = editing;
}

- (void)setCurrentValue:(NSInteger)currentValue {
    _currentValue = currentValue;
    self.textField.text = [NSString stringWithFormat:@"%ld", currentValue];
    [self checkTextfieldNumerWithUpdate];
}


#pragma mark- ==== layoutSubviews ====

- (void)layoutSubviews {
    [super layoutSubviews];
    _width  = self.frame.size.width;
    _height = self.frame.size.height;
    _textField.frame = CGRectMake(_height, 0, _width - 2 * _height, _height);
    _increaseButton.frame = CGRectMake(_width - _height, 0, _height, _height);
    if(_descreaseHide && _textField.text.integerValue < _minValue){
        _decreaseButton.frame = CGRectMake(_width - _height, 0, _height, _height);
    }
    else {
        _decreaseButton.frame = CGRectMake(0, 0, _height, _height);
    }
}


#pragma mark- ==== Action ====

- (void)touchDown:(UIButton *)sender {
    if(sender == _increaseButton){
        _timer = [NSTimer scheduledTimerWithTimeInterval:_longPressSpaceTime target:self selector:@selector(increase) userInfo:nil repeats:YES];
    }
    else {
        _timer = [NSTimer scheduledTimerWithTimeInterval:_longPressSpaceTime target:self selector:@selector(decrease) userInfo:nil repeats:YES];
    }
    [_timer fire];
}

- (void)touchUp:(UIButton *)sender {
    [self cleanTimer];
}

#pragma mark- ==== Method ====

/** 加操作 */
- (void)increase {
    [self checkTextfieldNumerWithUpdate];
    NSInteger number = self.textField.text.integerValue + 1;
    if(number <= _maxValue){
        if(_descreaseHide && number == _minValue){
            [self rotaionAnimationMedtoh];
            [UIView animateWithDuration:0.3f animations:^{
                _decreaseButton.frame = CGRectMake(0, 0, _height, _height);
                _decreaseButton.alpha = 1.0f;
            } completion:^(BOOL finished) {
                _textField.hidden = NO;
            }];
        }
        _textField.text = [NSString stringWithFormat:@"%ld", number];
        [self callBackWithInceaseStatus:YES];
    }
    else {
        if(_shakeAnimation){
            [self shakeAnimationMethod];
        }
    }
}

/** 减操作 */
- (void)decrease {
    [self checkTextfieldNumerWithUpdate];
    
    NSInteger number = self.textField.text.integerValue - 1;
    if(number >= _minValue){
        _textField.text = [NSString stringWithFormat:@"%ld", number];
        [self callBackWithInceaseStatus:NO];
    }
    else {
        /// 如果数字小于最小值，并且小于最小值隐藏减按钮 （则隐藏减按钮）
        if(_descreaseHide &&  number < _minValue){
            _textField.hidden = YES;
            _textField.text = [NSString stringWithFormat:@"%ld", _minValue - 1];
            
            [self callBackWithInceaseStatus:NO];
            [self rotaionAnimationMedtoh];
            [UIView animateWithDuration:0.3f animations:^{
                _decreaseButton.frame = CGRectMake(_width - _height, 0, _height, _height);
                _decreaseButton.alpha = 0;
            }];
        }
        else {
            if(_shakeAnimation){
                [self shakeAnimationMethod];
            }
        }
    }
}
/**
 * 检查输入框数字的合法性(是否在最大值和最小值之间)
 *
 * 如果是不在合法范围内进行更新操作
 */
- (void)checkTextfieldNumerWithUpdate {
    NSString *minValuesString = [NSString stringWithFormat:@"%ld", _minValue];
    NSString *maxValuesString = [NSString stringWithFormat:@"%ld", _maxValue];
    if([_textField.text cl_isNotBlank] == NO || _textField.text.integerValue < _minValue){
        _textField.text = _descreaseHide? [NSString stringWithFormat:@"%ld", _minValue - 1]:minValuesString;
    }
    _textField.text.integerValue > _maxValue? (_textField.text = maxValuesString):nil;
}

/**
 * 回调
 */
- (void)callBackWithInceaseStatus:(BOOL)increaseStatus {
    _resultBlock?_resultBlock(_textField.text.integerValue, increaseStatus):nil;
    if([_delegate respondsToSelector:@selector(cl_numberButton:number:increaseStatus:)]){
        [_delegate cl_numberButton:self number:_textField.text.integerValue increaseStatus:increaseStatus];
    }
}

/** 清除定时器 */
- (void)cleanTimer {
    if(_timer.isValid){
        [_timer invalidate];
        _timer = nil;
    }
}

#pragma mark- ==== Textfield delegate ====

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self checkTextfieldNumerWithUpdate];
    [self callBackWithInceaseStatus:NO];
}


#pragma mark- ==== 核心动画 ====

/** 抖动动画 */
- (void)shakeAnimationMethod {
    CAKeyframeAnimation *animtion = [CAKeyframeAnimation animationWithKeyPath:@"position.x"];
    CGFloat positionX = self.layer.position.x;
    animtion.values = @[@(positionX - 10), @(positionX), @(positionX + 10)];
    animtion.repeatCount = 3;
    animtion.duration = 0.07f;
    animtion.autoreverses = YES;
    [self.layer addAnimation:animtion forKey:nil];
}

/** 旋转动画 */
- (void)rotaionAnimationMedtoh {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    animation.toValue = @(M_PI * 2);
    animation.duration = 0.3f;
    animation.fillMode = kCAFillModeForwards;
    animation.removedOnCompletion = NO;
    [_decreaseButton.layer addAnimation:animation forKey:nil];
}


- (void)dealloc {
    [self cleanTimer];
}

@end


@implementation NSString (CLNumberButton)

- (BOOL)cl_isNotBlank {
    NSCharacterSet *blank = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    for(NSInteger i = 0; i < self.length; ++ i){
        unichar c = [self characterAtIndex:i];
        if(![blank characterIsMember:c]){
            return YES;
        }
    }
    return NO;
}


@end




























